
# Django 表单的作用
# 1) 处理用户输入并校验错误
# 2）渲染HTML输入框和错误信息
# 3）甚至可以保存数据到数据库

from django import forms
from django.core.exceptions import ValidationError

from .models import Item

# class ItemForm(forms.Form):
#     item_text = forms.CharField(
#         widget=forms.TextInput(attrs={
#             'placeholder': 'Enter a to-do item',
#             'class': 'form-control input-lg',
#         })
#     )

EMPTY_ITEM_ERROR = "You can't have an empty list item"
DUPLICATE_ITEM_ERROR = "You've already got this in your list"


# 使用ModelForm
class ItemForm(forms.ModelForm):
    class Meta:
        model = Item
        fields = ('text',)
        widgets = {
            'text': forms.TextInput(attrs={
                'placeholder': 'Enter a to-do item',
                'class': 'form-control input-lg',
            })
        }
        error_messages = {
            'text': {'required': EMPTY_ITEM_ERROR}
        }

    # 重写save方法保存外键
    def save(self, commit=True, for_list=None):
        self.instance.list = for_list
        return super().save(commit)


class ExistingListItemForm(ItemForm):
    # 重写__init__方法，让列表项知道添加到哪个列表上面去
    def __init__(self, for_list, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.instance.list = for_list

    # form.is_valid()会调用这个方法
    def validate_unique(self):
        try:
            self.instance.validate_unique()
        except ValidationError as e:
            e.error_dict = {'text': [DUPLICATE_ITEM_ERROR]}
            self._update_errors(e)

    def save(self, *a, **kw):
        return forms.ModelForm.save(self, *a, *kw)
